package com.xlong.controller;

import java.util.UUID;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.context.request.async.DeferredResult;

import com.xlong.BeanEntity.ResponseMsg;
import com.xlong.BeanEntity.TaskEntity;
import com.xlong.component.task.TaskQueue;
import com.xlong.core.CommUtils;

import lombok.extern.slf4j.Slf4j;

@RestController
@Slf4j
public class DeferredController {
	
    
    @Autowired
    private TaskQueue taskQueue;
    
    @Autowired
    private RabbitTemplate rabbitTemplate;  //使用RabbitTemplate,这提供了接收/发送等等方法
    
	@SuppressWarnings("static-access")
	@PostMapping("/deferred/test")
	public DeferredResult<ResponseMsg<JSONObject>> deferredtask(@RequestBody JSONObject map) throws Exception {
		 String taskId = UUID.randomUUID().toString();
        DeferredResult<ResponseMsg<JSONObject>> result = new DeferredResult<>(CommUtils.OUT_OF_TIME, CommUtils.OUT_OF_TIME_RESULT);

        result.onTimeout(() -> {
        	CommUtils.SETTABLE_FUTURE_LOADING_CACHE.invalidate(taskId);
            log.info("调用超时");            
        });

        result.onCompletion(() -> {
        	CommUtils.SETTABLE_FUTURE_LOADING_CACHE.invalidate(taskId);
            log.info("调用完成");
        });

        //并发，加锁
        //taskQueue.getInstance().put(result,map);
       
        CommUtils.SETTABLE_FUTURE_LOADING_CACHE.put(taskId, result);
    	//将消息携带绑定键值：TestDirectRouting 发送到交换机TestDirectExchange
        rabbitTemplate.convertAndSend("DirectExchange", "DirectRouting", JSONObject.toJSONString(new TaskEntity(taskId,result,map)) );

        

        return result;
    }
}
